// @author Tjzlo
// @version 2025/2/17 00:08

package com.old.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.old.dto.ActivityDTO;
import com.old.result.PageBean;
import com.old.result.PageResult;
import com.old.result.Result;
import com.old.service.ActivityService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/activity")
@RequiredArgsConstructor

public class ActivityController {

    private final ActivityService activityService;

    //添加活动
    @RequestMapping("/addActivity")
    public Result<PageResult> addActivity(@RequestBody ActivityDTO activityDTO) {
        log.info("{}用户发布活动", activityDTO.getAuthorId());
        activityService.addActivity(activityDTO);
        log.info("活动发布成功:发布者:{},活动名称:{}", activityDTO.getAuthorId(), activityDTO.getTitle());
        return Result.success();
    }

    //获取活动列表-分页
    @RequestMapping("/getActivityList")
    public Result getActivityList(@RequestParam(defaultValue = "1") Integer pageNo,
                                  @RequestParam(defaultValue = "10") Integer pageSize,
                                  @RequestParam(required = false) Integer sortBy,
                                  @RequestParam(required = false) Integer userId,
                                  @RequestParam(required = false) String searchTerms) throws JsonProcessingException {

        PageBean pageList = activityService.pageList(pageNo, pageSize, sortBy, searchTerms, userId);
        log.info("分页查询: 页码={} 页大小={} 搜索词={} 排序方式={} 总数={}", pageNo, pageSize, searchTerms, sortBy, pageList.getTotal());

        return Result.success(pageList);
    }

    //报名活动
    @PutMapping("/joinActivity")
    public Result<String> joinActivity(@RequestBody Map<String, Integer> request) {
        Integer activityId = request.get("activityId");
        Integer userId = request.get("userId");

        if (activityId == null || userId == null) {
            return Result.error("参数不能为空");
        }

        log.info("用户 {} 报名活动 {}", userId, activityId);
        return activityService.joinActivity(activityId, userId);
    }

    //取消活动
    @PutMapping("/noJoinActivity")
    public Result<String> noJoinActivity(@RequestBody Map<String, Integer> request) {
        Integer activityId = request.get("activityId");
        Integer userId = request.get("userId");

        // 参数校验
        if (activityId == null || userId == null) {
            return Result.error("参数不能为空");
        }

        log.info("用户 {} 取消报名活动 {}", userId, activityId);
        return activityService.cancelSignUp(activityId, userId);
    }

}
